const db = require("../config/mysql");

class StallModel {
    /** 列表+分页+搜索 */
    static async getList({ page = 1, pageSize = 10, name, status }) {
        page = Number(page) || 1;
        pageSize = Number(pageSize) || 10;

        let sql = `
            SELECT 
                stall_id, 
                name, 
                main_body, 
                contact_phone, 
                business_hours, 
                status, 
                created_at, 
                updated_at, 
                notes,
                position
            FROM stall 
            WHERE 1=1
        `;
        const args = [];

        // 模糊搜索档口名称
        if (name) {
            sql += ` AND name LIKE ?`;
            args.push(`%${name}%`);
        }

        // 状态筛选
        if (status !== undefined && status !== null) {
            sql += ` AND status = ?`;
            args.push(status);
        }

        // 查询总记录数
        const [totalRow] = await db.query(`
            SELECT COUNT(*) AS total FROM (${sql}) AS t
        `, args);
        const total = totalRow[0].total;

        // 添加分页和排序 - 修改为按stall_id升序排列
        sql += ` ORDER BY stall_id ASC LIMIT ? OFFSET ?`;
        args.push(pageSize, (page - 1) * pageSize);

        const list = await db.query(sql, args);
        return { total, list };
    }

    // 添加档口
    static async create(data) {
        const { name, main_body, contact_phone, business_hours, status, notes, position } = data;

        // 先查是否已存在
        const [rows] = await db.query(
            'SELECT stall_id FROM stall WHERE name = ? LIMIT 1',
            [name]
        );
        if (rows.length) {
            // 存在即抛错，控制器会 catch
            throw new Error('档口已存在');
        }

        // 不存在就插入
        const [result] = await db.query(
            `INSERT INTO stall
   (name, main_body, contact_phone, business_hours, status, notes, position)
 VALUES (?,?,?,?,?,?,?)`,
            [name, main_body, contact_phone, business_hours, status, notes, position]
        );

        // 返回插入的ID
        return result.insertId;
    }

    // 修改档口
    static async update(id, data) {
        console.log('后端接受的数据', data);

        // const fields = [];
        // const values = [];
        // // 构建更新字段和值的数组
        // for (const key in data) {
        //     fields.push(`${key} = ?`);
        //     values.push(data[key]);
        // }
        // if (!fields.length) return 0;
        // values.push(id);
        // // 执行更新操作并返回受影响的行数
        // const [result] = await db.query(`UPDATE stall SET ${fields.join(', ')} WHERE stall_id = ?`, values);
        const [result] = await db.query(
            `UPDATE stall 
     SET 
         name = ?, 
         main_body = ?, 
         contact_phone = ?, 
         business_hours = ?, 
         status = ?, 
         notes = ?,
         position = ?,
         updated_at = NOW() 
     WHERE stall_id = ?`,
            [
                data.name,
                data.main_body,
                data.contact_phone,
                data.business_hours,
                data.status,
                data.notes,
                data.position,
                id
            ]
        )

        return result.affectedRows;

    }

    // 删除档口(软删除)
    static async remove(id) {
        const [result] = await db.query(
            `UPDATE stall 
     SET status = 2, 
         updated_at = NOW() 
     WHERE stall_id = ?`,
            [id]
        );
        return result.affectedRows;
    }

    // 查看档口
    // StallModel.js
    static async getDetail(stallId) {
        const [rows] = await db.query(
            `
        SELECT 
            stall_id, 
            name, 
            main_body, 
            contact_phone, 
            business_hours, 
            status, 
            created_at, 
            updated_at, 
            notes,
            position
        FROM stall 
        WHERE stall_id = ?
        `,
            [stallId]
        );

        return rows[0]; // 返回第一个结果，或 null
    }
}

module.exports = StallModel;